package cn.blb.service.edu.service.impl;


import cn.blb.service.edu.entity.Chapter;
import cn.blb.service.edu.entity.CourseDescription;
import cn.blb.service.edu.entity.Video;
import cn.blb.service.edu.entity.vo.CourseInfoForm;
import cn.blb.service.base.handler.OssConfig;
import cn.blb.service.edu.mapper.CourseDescriptionMapper;
import cn.blb.service.edu.mapper.TeacherMapper;
import cn.blb.service.edu.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.blb.common.result.Result;
import cn.blb.service.edu.entity.Course;
import cn.blb.service.edu.entity.dto.CourseDto;
import cn.blb.service.edu.entity.vo.CourseQuery;
import cn.blb.service.edu.mapper.CourseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2022-03-17
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {


    private final VideoService videoService;
    private final OssConfig ossConfig;
    private final CourseDescriptionMapper courseDescriptionMapper;
    private final CourseDescriptionService courseDescriptionService;
    private final TeacherMapper teacherMapper;
    private final CourseMapper courseMapper;
    private final ChapterService chapterService;

    public CourseServiceImpl(VideoService videoService, OssConfig ossConfig, CourseDescriptionMapper courseDescriptionMapper, CourseDescriptionService courseDescriptionService, TeacherMapper teacherMapper, CourseMapper courseMapper, ChapterService chapterService) {
        this.videoService = videoService;
        this.ossConfig = ossConfig;
        this.courseDescriptionMapper = courseDescriptionMapper;
        this.courseDescriptionService = courseDescriptionService;
        this.teacherMapper = teacherMapper;
        this.courseMapper = courseMapper;
        this.chapterService = chapterService;
    }


    @Override
    public Result getCourseList(Page<CourseDto> page, QueryWrapper wrapper, CourseQuery courseQuery) {

        if (courseQuery != null) {

            String title = courseQuery.getTitle();
            String subjectId = courseQuery.getSubjectId();
            String subjectParentId = courseQuery.getSubjectParentId();
            String teacherId = courseQuery.getTeacherId();

            if (!StringUtils.isEmpty(title)) {
                wrapper.like("c.title", title);
            }
            if (!StringUtils.isEmpty(subjectId)) {
                wrapper.eq("c.subject_id", subjectId);
            }
            if (!StringUtils.isEmpty(teacherId)) {
                wrapper.eq("c.teacher_id", teacherId);
            }
            if (!StringUtils.isEmpty(subjectParentId)) {
                wrapper.eq("c.subject_parent_id", subjectParentId);
            }
        }
       Page<CourseDto> courseDtoPage = courseMapper.getCourseDtoBySearch(page, wrapper);

       List<CourseDto> records = courseDtoPage.getRecords();

     records.forEach(record->{
           record.setTeacher(teacherMapper.selectById(record.getTeacherId()));
        });
        courseDtoPage.getRecords().forEach(
                courseDto ->  courseDto.setStatus("Draft".equals(courseDto.getStatus()) ? "未发布":"已发布").setCover(courseDto.getCover())
        );
        return Result.ok().setData("items",courseDtoPage.getRecords()).setData("current",courseDtoPage.getCurrent()).setData("total",courseDtoPage.getTotal()).setData("pages",courseDtoPage.getPages());
    }

    @Override
    public CourseInfoForm getCourseInfoFormById(String id) {
        CourseInfoForm courseInfoForm = new CourseInfoForm();
        // 1.获取course
        // 1.1 根据id查询
        Course course = baseMapper.selectById(id);
        // 1.2 将course的值付给courseInfoForm
        BeanUtils.copyProperties(course, courseInfoForm);

        // 2.获取courseDescription
        // 2.1 查询
        CourseDescription courseDescription = courseDescriptionMapper.selectById(id);
        if (courseDescription!=null) {
            courseInfoForm.setDescription(courseDescription.getDescription());
        }

        // 3.将course和courseDescription组装成courseInfoForm
        return courseInfoForm;
    }

    @Override
    public void updateCourseInfoById(CourseInfoForm courseInfoForm) {
        // 1.修改course
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        boolean b = this.updateById(course);

        // 2.修改Description
        CourseDescription description = new CourseDescription();
        description.setDescription(courseInfoForm.getDescription());
        description.setId(course.getId());
        courseDescriptionMapper.updateById(description);
    }

    @Override
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {
        String courseId = "";
        // 1.保存基本信息
        Course course = new Course();
        course.setStatus(Course.COURSE_DRAFT); // 设置状态(默认初次添加为未发布状态)
        // 复制相同对象到另一个对象 courseInfoForm - > course
        BeanUtils.copyProperties(courseInfoForm, course);
        boolean save = this.save(course);// 保存

        courseId = course.getId();

        // 2.保存课程简介
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        // 保存课程id，课程表的id跟课程简介表的id要保持一致
        courseDescription.setId(courseId);
        boolean resultDescription = courseDescriptionService.save(courseDescription);

        return courseId;
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean removeCourseById(String id) {
//        先删除video,再删chapter，再删course
//        先找到自身下面所有的video和chapter
//        在其他所有都成功的情况下才能进行删除course
        boolean remove = true;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("course_id", id);
        List<Video> videoList = videoService.list(wrapper);
        List<Chapter> chapterList = chapterService.list(wrapper);

        if (videoList.size() > 0) {
            remove = videoService.removeBatchByIds(videoList);
            if (remove && chapterList.size() > 0) {
                remove = chapterService.removeByIds(chapterList);
            }
        }
        if (remove) {
            remove = this.removeById(id);
        }
        return remove;
    }

    @Override
    public CourseDto getCourseDtoById(String id) {
        CourseDto courseDto = courseMapper.getCourseById(id);
        courseDto.setCover(ossConfig.getOssWebUrl() + courseDto.getCover());
        return courseDto;
    }

    @Override
    public CourseDto backCourseDtoById(String id) {
        CourseDto courseDto = courseMapper.getCourseById(id);
        courseDto.setCover(ossConfig.getOssWebUrl() + courseDto.getCover());
        return courseDto;
    }
}
